package com.cxh.rmsq.net.newNet

import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import com.aleyn.mvvm.utils.ActivityCollector
import com.cxh.rmsq.SealApp
import com.cxh.rmsq.im.IMManager
import com.cxh.rmsq.ui.activity.LoginActivity
import com.cxh.rmsq.utils.loge
import com.google.gson.Gson
import io.rong.callkit.util.SPUtils
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import java.nio.charset.Charset

/**
 * Created by 赵杰 on 2019-10-15.
 */

class AppHttpInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalResponse = chain.proceed(chain.request())
        val responseBody = originalResponse.body
        val source = responseBody!!.source()
        source.request(java.lang.Long.MAX_VALUE) // Buffer the entire body.
        val buffer = source.buffer()
        var charset = Charset.forName("UTF-8")
        val contentType = responseBody.contentType()
        if (contentType != null) {
            charset = contentType.charset(Charset.forName("UTF-8"))
        }

        // 添加用户登录认证
//            String auth = preferences.getString(NetConstant.API_SP_KEY_NET_HEADER_AUTH, null);
        val auth = SPUtils.get(SealApp.getApplication(), "accessToken", "").toString()
        Log.e("token",  auth)
        loge(buffer.clone().readString(charset))

        val entity = Gson().fromJson<BaseResultEntity<Any>>(
            buffer.clone().readString(charset),
            BaseResultEntity::class.java
        )
//        ActivityCollector.getCurrentActivity().loading(false)
        if (entity != null) {
            /*when (entity.code) {
//                500, 9999 -> {
//                    Handler(Looper.getMainLooper()).post {
//                        ActivityCollector.getCurrentActivity().toast(entity.msg)
//                    }
//                }
                401 -> {
                    Handler(Looper.getMainLooper()).post {
                        ActivityCollector.finishAll()
                        ActivityCollector.getCurrentActivity().toast("会话失效，请重新登录！")
                        ActivityCollector.getCurrentActivity().startActivity<CodeLoginActivity>()
//                        ActivityCollector.getCurrentActivity().finish()
                    }
                }
            }
*/
            if (entity.code == 401) {
                if (!TextUtils.isEmpty(SPUtils.get(SealApp.getApplication(), "accessToken", "").toString())) {
                    SPUtils.put(SealApp.getApplication(), "token", "")
                    Handler(Looper.getMainLooper()).post {
                        ActivityCollector.finishAll()
                        SPUtils.clear(SealApp.getApplication())
                        com.blankj.utilcode.util.SPUtils.getInstance().clear()
                        IMManager.getInstance().logoutAndClear()
                        Toast.makeText(SealApp.getApplication(), "会话失效，请重新登录！", Toast.LENGTH_SHORT).show()
                        ActivityCollector.getCurrentActivity().startActivity(
                            Intent(ActivityCollector.getCurrentActivity(), LoginActivity::class.java)
                        )
                    }
                }
            }
        }
        return originalResponse
    }
}